package com.dxq.test.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.dxq.test.App;
import com.dxq.test.common.AppManager;
import com.dxq.test.R;
import com.dxq.test.db.Feed;
import com.dxq.test.db.FeedGroupFood;
import com.dxq.test.db.Food;
import com.dxq.test.db.Group;
import com.dxq.test.db.Label;
import com.dxq.test.db.Pasture;
import com.dxq.test.db.TablesDao;
import com.dxq.test.utils.DialogClickListener;
import com.dxq.test.utils.DialogListClickListener;
import com.dxq.test.utils.MyUtil;
import com.j256.ormlite.dao.ForeignCollection;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Author: zsh
 * Date: 2023/11/18
 * Describe: 饲喂添加、修改、删除页面
 */
public class FeedAddActivity extends AppCompatActivity implements View.OnClickListener, OnDateSetListener {

    public TablesDao tablesDao;

    private ImageView ivBack;
    private TextView tvTitle, tvSet;
    private LinearLayout llCode, llTime;
    private TextView tvCode, tvGroup, tvFood, tvTime;
    private Button btnSubmit;

    private TimePickerDialog mDialogAllTime;//选择时间控件

    private Feed feed;

    private Group selectGroup;
    private Food selectFood;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //添加Activity到堆栈
        AppManager.getAppManager().addActivity(this);
        setContentView(R.layout.activity_feed_add);
        feed = (Feed) getIntent().getSerializableExtra("feed");
        tablesDao = new TablesDao(this);
        initView();
        initTimePicker();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在appManager结束当前activity
        AppManager.getAppManager().finishActivity(this);
    }

    private void initView() {
        ivBack = findViewById(R.id.ivBack);
        tvTitle = findViewById(R.id.tvTitle);
        tvSet = findViewById(R.id.tvSet);
        llCode = this.findViewById(R.id.llCode);
        llTime = this.findViewById(R.id.llTime);
        tvCode = findViewById(R.id.tvCode);
        tvGroup = findViewById(R.id.tvGroup);
        tvFood = findViewById(R.id.tvFood);
        tvTime = findViewById(R.id.tvTime);
        btnSubmit = findViewById(R.id.btnSubmit);
        tvSet.setText("删除");
        if (null == feed) {
            tvTitle.setText("添加饲喂");
            tvSet.setVisibility(View.GONE);
            llCode.setVisibility(View.GONE);
            llTime.setVisibility(View.GONE);
        } else {
            tvTitle.setText("修改饲喂");
            tvSet.setVisibility(View.VISIBLE);
            llCode.setVisibility(View.VISIBLE);
            llTime.setVisibility(View.VISIBLE);
            tvCode.setText(feed.getCode());
            selectGroup = feed.getGroup();
            selectFood = feed.getFood();
            tvGroup.setText(selectGroup.getName());
            tvFood.setText(selectFood.getName());
            tvTime.setText(feed.getTime());
        }

        ivBack.setOnClickListener(this);
        tvSet.setOnClickListener(this);
        tvGroup.setOnClickListener(this);
        tvFood.setOnClickListener(this);
        //tvTime.setOnClickListener(this);
        btnSubmit.setOnClickListener(this);
    }

    private void initTimePicker() {
        //初始化时间控件
        long tenYears = 10L * 365 * 1000 * 60 * 60 * 24L;
        mDialogAllTime = new TimePickerDialog.Builder()
                .setCallBack(FeedAddActivity.this)
                .setCancelStringId("取消")
                .setSureStringId("确定")
                .setTitleStringId("选择时间")
                .setYearText("年")
                .setMonthText("月")
                .setDayText("日")
                .setHourText("时")
                .setMinuteText("分")
                .setCyclic(false)
                .setMinMillseconds(System.currentTimeMillis())
//                .setMaxMillseconds(System.currentTimeMillis() + 3 * tenYears)
                .setCurrentMillseconds(System.currentTimeMillis())
                .setThemeColor(getResources().getColor(R.color.timepicker_dialog_bg))
                .setType(Type.ALL)
                .setWheelItemTextNormalColor(getResources().getColor(R.color.timetimepicker_default_text_color))
                .setWheelItemTextSelectorColor(getResources().getColor(R.color.blu))
                .setWheelItemTextSize(12)
                .build();
    }

    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        tvTime.setText(TimeUtils.millis2String(millseconds));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                this.finish();
                break;

            case R.id.tvSet://删除
                MyUtil.normalDialog(FeedAddActivity.this, "操作提示", "是否删除饲喂信息？",
                        "取消", "确定", new DialogClickListener() {

                            @Override
                            public void onNegativeClick() {

                            }

                            @Override
                            public void onPositiveClick() {
                                deleteFeed();
                            }
                        });
                break;

            case R.id.tvGroup://选择分群
                selectGroup();
                break;

            case R.id.tvFood://选择饲料
                selectFood();
                break;

            case R.id.tvTime://选择饲喂时间
                if (null == feed)
                    mDialogAllTime.show(getSupportFragmentManager(), "all");
                break;

            case R.id.btnSubmit://提交
                submit();
                break;
        }
    }

    private void selectGroup() {
        List<Group> list = new ArrayList<>();
        Pasture pasture = tablesDao.queryPastureById(App.select_pasture_id);
        if (null != pasture) {
            ForeignCollection<Group> groups = pasture.getGroups();
            for (Group group : groups) {
                list.add(group);
            }
            if (!ObjectUtils.isEmpty(list)) {
                String[] arr = new String[list.size()];//创建数组，只是分配了内存，但是没有进行赋值
                for (int i = 0; i < list.size(); i++) {
                    arr[i] = list.get(i).getName();
                }
                MyUtil.itemListDialog(FeedAddActivity.this, "选择分群", arr,
                        new DialogListClickListener() {
                            @Override
                            public void onClick(int position) {
                                selectGroup = list.get(position);
                                tvGroup.setText(selectGroup.getName());
                            }
                        });
            } else {
                ToastUtils.showShort("暂无分群数据");
            }
        } else {
            ToastUtils.showShort("暂无分群数据");
        }
    }

    private void selectFood() {
        List<Food> list = new ArrayList<>();
        Pasture pasture = tablesDao.queryPastureById(App.select_pasture_id);
        if (null != pasture) {
            ForeignCollection<Food> foods = pasture.getFoods();
            for (Food food : foods) {
                list.add(food);
            }
            if (!ObjectUtils.isEmpty(list)) {
                String[] arr = new String[list.size()];//只是分配了内存，但是没有进行赋值
                for (int i = 0; i < list.size(); i++) {
                    arr[i] = list.get(i).getName();
                }
                MyUtil.itemListDialog(FeedAddActivity.this, "选择饲料", arr,
                        new DialogListClickListener() {
                            @Override
                            public void onClick(int position) {
                                selectFood = list.get(position);
                                tvFood.setText(selectFood.getName());
                            }
                        });
            } else {
                ToastUtils.showShort("暂无饲料数据");
            }
        } else {
            ToastUtils.showShort("暂无饲料数据");
        }
    }

    //删除feed
    private void deleteFeed() {
        //判断该饲料是否已与饲喂关联
        int result = tablesDao.deleteFeed(feed);
        if (result != 1) {
            ToastUtils.showShort("删除失败, feed");
            return;
        }

        List<FeedGroupFood> feedGroupFoods = tablesDao.queryFeedGroupFoodByFeed(feed);
        int res = tablesDao.deleteFeedGroupFood(feedGroupFoods);
        ToastUtils.showShort("删除成功");
        this.finish();
    }

    private void submit() {
        String groupName = tvGroup.getText().toString();
        String foodName = tvFood.getText().toString();
        if (groupName.equals("")) {
            ToastUtils.showShort("选择分群");
            return;
        }
        if (foodName.equals("")) {
            ToastUtils.showShort("选择饲料");
            return;
        }
        if (null == feed) {
            //查询当前所选择牧场
            Pasture pasture = tablesDao.queryPastureById(App.select_pasture_id);
            //新增
            String code = "SL" + MyUtil.date2String(new Date());
            Feed f = new Feed(code, TimeUtils.getNowString(), pasture);
            //1、创建饲喂
            int result = tablesDao.insertFeed(f);
            if (result == 1) {
                //2、创建关联数据
                FeedGroupFood feedGroupFood = new FeedGroupFood(f, selectGroup, selectFood);
                int res = tablesDao.insertFeedGroupFood(feedGroupFood);
                if (res == 1) {
                    //3、创建成功，返回页面
                    ToastUtils.showShort("新增成功");
                    this.finish();
                    return;
                } else {
                    //4、创建失败，删除创建成功的饲喂数据
                    ToastUtils.showShort("新增失败，feed");
                    tablesDao.deleteFeed(f);
                }
            }
            ToastUtils.showShort("新增失败，feed");
        } else {
            //修改
            //如果修改了分群、饲料，需要更改关联表信息
            if (selectGroup != null && !selectGroup.getName().equals(feed.getGroup().getName()) ||
                    selectFood != null && !selectFood.getName().equals(feed.getFood().getName())) {
                //1、查询出旧的关联数据
                List<FeedGroupFood> feedGroupFoods = tablesDao.queryFeedGroupFoodByFeed(feed);
                //2、删除旧的关联数据
                if (null != feedGroupFoods && feedGroupFoods.size() > 0) {
                    tablesDao.deleteFeedGroupFood(feedGroupFoods.get(0));
                    //3、新增新的关联数据
                    FeedGroupFood feedGroupFood = new FeedGroupFood(feed, selectGroup, selectFood);
                    tablesDao.insertFeedGroupFood(feedGroupFood);
                }
            }
            Feed f = tablesDao.queryFeedById(feed.getFeed_id());
            //f.setTime(time);
            int result = tablesDao.updateFeed(f);
            if (result == 1) {
                ToastUtils.showShort("更新成功");
                this.finish();
                return;
            }
            ToastUtils.showShort("更新失败，feed");
        }
    }

    @Override
    public void onBackPressed() {
        this.finish();
    }
}
